package com.linkage.event.service.impl;

import cn.hutool.core.lang.UUID;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linkage.event.pojo.dao.TrainMessageMapper;
import com.linkage.event.pojo.entity.TrainMessage;
import com.linkage.event.service.TrainMessageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class TrainMessageServiceImpl implements TrainMessageService {
    @Resource
    private TrainMessageMapper trainMessageMapper;


    @Override
    public TrainMessage queryTrainInfo(String id) {
        return trainMessageMapper.selectByPrimaryKey(id);
    }

    @Override
    public void insertTrainInfo(TrainMessage message) {
        message.setId(UUID.fastUUID().toString(true));
        message.setCreateTime(new Date());
        trainMessageMapper.insertSelective(message);
    }

    @Override
    public void updateTrainInfo(TrainMessage message) {
        trainMessageMapper.updateByPrimaryKeySelective(message);
    }

    @Override
    public PageInfo<TrainMessage> queryListByPage(TrainMessage message, int page, int pageSize) {
        PageHelper.startPage(page,pageSize);
        List<TrainMessage> messageList = trainMessageMapper.queryListByPage(message);
        messageList.forEach(x -> {
            x.setPicUrlList(getImgSrc(x.getContent()));
        });
        return new PageInfo<TrainMessage>(messageList);
    }

    @Override
    public void delete(String id) {
        trainMessageMapper.deleteByPrimaryKey(id);
    }

    /**
     * 从html字符串中提取图片地址
     * @param htmlStr
     * @return
     */
    private static List<String> getImgSrc(String htmlStr) {
        String img = "";
        Pattern p_image;
        Matcher m_image;
        List<String> pics = new ArrayList<String>();
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }
}
